<template>
  <el-dialog
    :visible.sync="dialogShow"
    :before-close="check"
    title="查看"
    width="75%"
  >
    <el-card
      class="box-card"
      :body-style="{ height: '90px' }"
    >
      <div class="inputall">
        <div class="rolename">
          <span>角色名称：</span>
          <el-input
            v-model="roleNames"
            disabled
            class="roleNameInput"
            suffix-icon="el-icon-s-custom"
            size="mini"
          />
        </div>
        <div class="rolenote">
          <span>备注：</span>
          <el-input
            v-model="roleNote"
            type="textarea"
            rows="2"
            disabled
            class="roleNameInput"
            suffix-icon="el-icon-s-custom"
            size="mini"
          />
        </div>
      </div>
    </el-card>
    <el-card>
      <el-tabs v-model="indexVal" tab-position="left">
        <el-tab-pane
          v-for="(item, index) in list"
          :key="item.id"
          :label="item.powerName"
          :name="item.powerName"
        >
          <!-- list是整个大数组 -->
          <el-checkbox-group v-model="checkList[index]">
            <div
              v-for="(menu, indexx) in item.children"
              :key="menu.id"
              class="menu"
            >
              <!-- menu是每个模块的 -->
              <span>{{ menu.powerName }}</span>
              <div class="btnall">
                <el-checkbox
                  size="small"
                  disabled
                  :label="indexx"
                  @change="getAllVal(menu.children, index, indexx)"
                >全选</el-checkbox>
                <!-- btn是每个按钮 :label="menu.children" -->
                <el-checkbox
                  v-for="btn in menu.children"
                  :key="btn.id"
                  :label="btn.powerCode"
                  border
                  size="small"
                  disabled
                >{{ btn.powerName }}</el-checkbox>
              </div>
            </div>
          </el-checkbox-group>
        </el-tab-pane>
      </el-tabs>
      <div v-show="false" class="btnpower">
        <el-button
          type="primary"
          size="mini"
          style="width:15%"
          round
          class="btnpowerFirst"
          @click="saveResult"
        >保存</el-button>
        <el-button
          plain
          size="mini"
          style="width:15%"
          round
          type="primary"
          @click="check"
        >取消</el-button>
      </div>
    </el-card>
  </el-dialog>
</template>
<script>
import { getDetail, changeRole } from '@/api/rolesetting'
export default {
  name: 'EditRole',
  props: {
    dialogWatch: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: Number,
      default: 0
    },
    roleName: {
      type: String,
      default: ''
    },
    roleDesc: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogShow: false,
      indexVal: '用户管理',
      roleNames: '',
      roleNote: '',
      roleIds: 0,
      list: null,
      status: [],
      checkList: [],
      allPower: []
    }
  },
  watch: {
    dialogWatch(newVal) {
      this.dialogShow = newVal
      this.roleIds = this.roleId
      this.roleNames = this.roleName
      this.roleNote = this.roleDesc
      if (newVal) {
        this.loadNewList()
      }
    }
  },
  methods: {
    // 请求新列表
    loadNewList() {
      getDetail({ id: this.roleIds })
        .then(response => {
          // 创建全选数组以及渲染列表
          var bigArrLen = response.data.powers.length
          /* var allPower = JSON.parse(JSON.stringify(response.data.powers))
          var oneArr = allPower.flatMap(item => {
            var middle = {
              id: item.id,
              parentCode: item.parentCode,
              powerClass: item.powerClass,
              powerCode: item.powerCode,
              powerName: item.powerName,
              powerRemark: item.powerRemark,
              powerType: item.powerType,
              sortNum: item.sortNum
            }
            var middleChildren = []
            if (item.children && item.children.length > 0) {
              middleChildren = item.children
            }
            middleChildren.push(middle)
            return middleChildren
          })
          var lastResult = oneArr.flatMap(item => {
            var middSon = {
              id: item.id,
              parentCode: item.parentCode,
              powerClass: item.powerClass,
              powerCode: item.powerCode,
              powerName: item.powerName,
              powerRemark: item.powerRemark,
              powerType: item.powerType,
              sortNum: item.sortNum
            }
            var dauSon = []
            if (item.children && item.children.length > 0) {
              dauSon = item.children
            }
            dauSon.push(middSon)
            return dauSon
          })
          this.allPower = lastResult */
          /* for (let i = 0; i < allPower.length; i++) {
            if (allPower[i].children && allpower[i].chidlren.length > 0) {
              var son = allpower[i].chidlren
              for (let j = 0; j < son.length; j++) {
                if (son[j].chidlren && son[j].chidlren.length > 0) {
                  var dau = son[j].chidlren
                  for (let k = 0; k < dau.length; k++) {
                    if ()
                  }
                }
              }
            }
          } */
          var lastData = [] // 全选
          var systemPower = []
          if (bigArrLen === 0) {
            this.$message({
              message: '请求列表失败，请重试',
              type: 'error'
            })
            return false
          }
          var bigArr = new Array(bigArrLen).fill([])
          this.checkList = bigArr
          var req = response.data.powers
          for (let i = 0; i < req.length; i++) {
            // 加入system
            systemPower.push(req[i].powerCode)
            // 全选按钮
            var newData = bigArr[i].concat(req[i].children)
            lastData.push(newData)
          }
          // 创建替代品
          var koa = []
          for (let v = 0; v < bigArrLen; v++) {
            var itemz = []
            koa.push(itemz)
          }
          var pow = response.data.hadPowers
          if (pow.length !== 0) {
            // 开始加入自定义
            for (let y = 0; y < systemPower.length; y++) {
              for (let p = 0; p < pow.length; p++) {
                if (
                  pow[p].powerType !== 'system' &&
                  pow[p].powerType !== 'menu'
                ) {
                  var findIndex = pow[p].powerCode.indexOf('-')
                  var systemCode = pow[p].powerCode.substring(0, findIndex)
                  if (systemPower[y] === systemCode) {
                    koa[y].push(pow[p].powerCode)
                  }
                }
              }
            }
            this.checkList = koa
          }
          // 全选用
          for (let j = 0; j < lastData.length; j++) {
            lastData[j].fill(true)
          }
          this.status = lastData
          const { powers } = response.data
          this.list = powers
          console.log('==============')
          console.log(this.list)
          console.log(this.checkList)
          console.log('==============')
        })
        .catch(() => {
          this.$message({
            message: '请求列表失败，请重试',
            type: 'error'
          })
        })
    },
    check: function() {
      this.$emit('closeWatchDialog')
      this.dialogShow = false
      setTimeout(() => {
        this.indexVal = '用户管理'
      }, 1000)
    },
    // 保存
    saveResult: function() {
      var result = []
      // 合并数组
      this.checkList.forEach(function(item) {
        result.push(...item)
      })
      // console.log(result)
      // 去除全选索引
      var newResult = []
      if (result.length > 0) {
        result.forEach(function(item) {
          if (item !== null && item !== '' && isNaN(item)) {
            newResult.push(item)
          }
        })
        // console.log(newResult) // 保存的值
        var newList = [] // 重组后的btn列表
        var systemMenuList = [] // 重组后的system && 重组后的menu列表列表
        // list button && list menu && list systenm重组
        this.list.forEach(function(item) {
          if (item.children.length > 0) {
            item.children.forEach(function(params) {
              if (params.children && params.children.length > 0) {
                params.children.forEach(function(val) {
                  newList.push(val)
                })
                delete params.children
                systemMenuList.push(params)
              }
            })
            delete item.children
            systemMenuList.push(item) // 把system存入
          }
        })
        // 开始查找
        var lastValue = []
        newList.forEach(function(relVal) {
          newResult.forEach(function(relSmall) {
            if (relVal.powerCode === relSmall) {
              lastValue.push(relVal)
            }
          })
        })
        // console.log(systemMenuList)
        var arrAll = []
        // 找到已有btn情况下的system
        for (let i = 0; i < systemMenuList.length; i++) {
          for (let j = 0; j < lastValue.length; j++) {
            const systemIndex = lastValue[j].parentCode.indexOf('-')
            const system = lastValue[j].parentCode.substring(0, systemIndex)
            const menuIndex = lastValue[j].parentCode
            if (system === systemMenuList[i].powerCode && systemMenuList[i].powerType === 'system') {
              arrAll.push(systemMenuList[i])
              break
            }
            if (menuIndex === systemMenuList[i].powerCode && systemMenuList[i].powerType === 'menu') {
              arrAll.push(systemMenuList[i])
              break
            }
          }
        }
        // console.log(arrAll)
        var lastAllResult = lastValue.concat(arrAll)
        // allPower
        // var realResult = []
        /* for (let i = 0; i < lastAllResult.length; i++) {
          for (let j = 0; j < this.allPower.length; j++) {
            if (this.allPower[j].powerCode === lastAllResult[i]) {
              realResult.push(this.allPower[j])
            }
          }
        } */
        var lastDataArr = {
          id: this.roleIds,
          name: this.roleNames,
          remark: this.roleNote,
          powers: lastAllResult
        }
        changeRole(lastDataArr).then(res => {
          if (res.resultCode === '0000') {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.check()
          }
        })
      } else {
        // 没权限
        lastValue = []
      }
      // ajax
      // console.log(lastValue)
      // this.check()
    },
    // 全选
    getAllVal: function(val, num, indexx) {
      var that = this
      var status = this.status[num][indexx]
      // 全选
      if (val.length > 0) {
        if (status) {
          val.forEach(function(item) {
            // **去重**
            if (that.checkList[num].indexOf(item.powerCode) === -1) {
              that.checkList[num].push(item.powerCode)
            }
          })
          this.status[num][indexx] = false
        } else {
          val.forEach(function(item) {
            // 判断是否有值
            var rank = that.checkList[num].indexOf(item.powerCode)
            if (rank !== -1) {
              that.checkList[num].splice(rank, 1)
            }
          })
          this.status[num][indexx] = true
        }
      }
    }
    /* watchChange: function(index,indexx,indexxx) {
      console.log(this.checkList)
      // this.list[index].children[indexx].children[indexxx].
    } */
  }
}
</script>
<style scoped>
.checkbox-per {
  margin-top: -43px;
  padding-left: 180px;
}
.btnList {
  width: 200px;
  text-align: center;
  margin: 0 auto;
}
.btn {
  margin-bottom: -20px !important;
  padding-bottom: 10px;
}
.marginBtn {
  margin-left: 30px;
}
.leftPosition {
  margin-left: 20px;
}
.add {
  font-size: 100px;
}
.inputall {
  display: flex;
  width: 100%;
  height: 32px;
  line-height: 32px;
  justify-content: space-around;
}
.rolename,
.rolenote {
  font-weight: bold;
}
.rolename::before{
  content: "*";
  float: left;
  color: red;
}
.rolename span,
.rolenote span {
  float: left;
  width: 80px;
  display: block;
}
.box-card {
  margin-bottom: 10px;
  margin-top: -20px;
}
.roleNameInput {
  float: left;
  width: 200px;
}
.menu {
  width: 98%;
  margin: 15px 5px 5px 5px;
  /* box-shadow: 0 1px 2px 0 rgba(0,0,0,.1); */
  border-bottom: 1px solid #ccc;
  padding: 10px 10px 0px 10px;
}
.menu span {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 13px;
  display: inline-block;
}

.btnall {
  margin-left: 10px;
}
.btnpower {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.btnpowerFirst {
  margin-right: 10px;
}
</style>
<style>
.el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0 !important;
  margin-bottom: 10px !important;
}
.el-checkbox.is-bordered.el-checkbox--small {
  margin-bottom: 10px !important;
}
</style>
